#!/bin/sh

# don't run normal rc stuff if factory=1
# used by manufacturing to verify boards on a clean system
if [ "$(kernopt factory)" = "1" ]; then
  echo "$0: found factory=1, exiting" >/dev/kmsg
  exit 0
fi

# /usr should take precedence over /
export PATH=/usr/bin:/usr/sbin:/bin:/sbin:.


# Send our output (and that of our child processes) to /dev/kmsg so it'll be
# timestamped and uploaded along with the kernel messages.  We can't use
# logger here because syslogd isn't started yet, and anyway, doing it
# this way guarantees all our boot messages are in exactly the right order.
# (otherwise kernel task switching could result in kernel driver messages
# showing up before the userspace messages that triggered them)
exec >/dev/kmsg 2>&1

# TODO(apenwarr): mkdir -p seems buggy across symlinks.
#  Strangely doing the 'cd' commands below seems to make things like
#  'mkdir -p /var/lock/whatever' start working, implying it's caused by a bug
#  in the kernel somewhere (perhaps in NFS).
mkdir /tmp/run
chmod 777 /tmp/run
(cd /var/lock)
(cd /var/cache)
(cd /var/log)

. /etc/utils.sh

# Start all init scripts in /etc/init.d
# executing them in numerical order.
#
for i in /etc/init.d/S[0-9]?*; do

  # Ignore if /config/init_skiplist exists and contains the name of the file
  if [ -e /config/init_skiplist ] &&
     filecontains "$i" /config/init_skiplist; then
    echo "Skipping $i"
    continue
  fi

  # Ignore dangling symlinks (if any).
  [ ! -f "$i" ] && continue

  # Ignore backup files (filename~) created by editors (mostly for nfsroot)
  [ "$i" != "${i%~}" ] && continue

  echo "---- ${i##*/}" >&2

  case "$i" in
    *.sh)
      # Source shell script for speed.
      (
         trap - INT QUIT TSTP
         set start
         . $i
      )
      ;;
    *)
      # No sh extension, so fork subprocess.
      $i start
      ;;
  esac

  # Mark init script as done, so s6-rc services can depend on it.
  : >/tmp/run/${i##*/}.init
done

echo
echo "/etc/init.d/rcS: done." >&2
